package ar.edu.unlu.sistemas.movirdroid.business.ws;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.kobjects.base64.Base64;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import ar.edu.unlu.sistemas.movirdroid.android.AppService;
import ar.edu.unlu.sistemas.movirdroid.business.peer.Peer;
import ar.edu.unlu.sistemas.movirdroid.business.util.Logger;
import ar.edu.unlu.sistemas.movirdroid.business.util.Params;
import ar.edu.unlu.sistemas.ws.business.PeerWS;
import ar.edu.unlu.sistemas.ws.business.QueryResultVO;
import ar.edu.unlu.sistemas.ws.business.ResourceDescriptionWS;

public class MovirdroidWSInterface {
	
	
	
	private static final String NAMESPACE = "http://ws.sistemas.unlu.edu.ar/";
	private static String URL="http://192.168.1.2:8080/movirdroid_ws/services/movirdroidwebservice?wsdl"; 
	private static final String SOAP_ACTION =  "http://ws.sistemas.unlu.edu.ar/";
	private Peer peerClient;
	
	public MovirdroidWSInterface(Peer peerClient) {
		this.peerClient = peerClient;
	}
	
	public Integer sayHello() {
		PeerWS peerWS = this.peerClient.getWSObject();
		SoapObject request = new SoapObject(NAMESPACE, "sayHello");
		PropertyInfo propInfo = new PropertyInfo();
		propInfo.setName("arg0");
		propInfo.setValue(peerWS);
		propInfo.setType(peerWS.getClass());
		request.addProperty(propInfo);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
		envelope.setOutputSoapObject(request);
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
		String result = null;
		Integer id = -2;
		try {
			androidHttpTransport.call(SOAP_ACTION, envelope);
			SoapPrimitive  resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();
			result = resultsRequestSOAP.toString();
			id = new Integer(result);
		} catch (Exception e) {
			Logger.logError(MovirdroidWSInterface.class.getSimpleName(), "Error al agregar al peer", e);
		}
		if (id > 0 && !id.equals(peerClient.getId())){
			Params.PEER_ID = id;
			AppService.instance.savePreferences(null);
			peerClient.setId(id);
		}
		return id;
	}
	
	public List<QueryResultVO> query(String query) {
		PeerWS peerWS = this.peerClient.getWSObject();
		SoapObject request = new SoapObject(NAMESPACE, "query");
		PropertyInfo propInfo = new PropertyInfo();
		propInfo.setName("arg0");
		propInfo.setValue(peerWS);
		propInfo.setType(peerWS.getClass());
		request.addProperty(propInfo);
		request.addProperty("arg1", query);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
		envelope.setOutputSoapObject(request);
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
		List<QueryResultVO> ranking = new ArrayList<QueryResultVO>();
		try {
			androidHttpTransport.call(SOAP_ACTION, envelope);
			SoapObject  resultsRequestSOAP = (SoapObject) envelope.getResponse();
			SoapObject results = (SoapObject) resultsRequestSOAP.getProperty(0);
			int count = results.getPropertyCount();
			SoapObject resultElement;
			QueryResultVO result;
		
			for (int i = 0; i < count; i++) {
				resultElement = (SoapObject) results.getProperty(i);
				
				result = new QueryResultVO();
				result.setAddress(resultElement.getProperty(0).toString());
				result.setDocName(resultElement.getProperty(1).toString());
				result.setPort(new Integer(resultElement.getProperty(2).toString()));
				result.setValue(new Float(resultElement.getProperty(3).toString()));
		        
		        ranking.add(result);
		        
		    }

		} catch (Exception e) {
			Logger.logError(MovirdroidWSInterface.class.getSimpleName(), "Ocurrio un error con el mensaje query del WS", e);
		}
		return ranking;
	}

	public String putIndex(ResourceDescriptionWS resourceDescrip) {
		PeerWS peerWS = this.peerClient.getWSObject();
		SoapObject request = new SoapObject(NAMESPACE, "putIndex");
		String id = null;
		try {
			PropertyInfo propInfo = new PropertyInfo();
			propInfo.setName("arg0");
			propInfo.setValue(peerWS);
			propInfo.setType(peerWS.getClass());
			request.addProperty(propInfo);
			//SERILIZAR LA DESCRIPCION DEL RECURSO Y MANDARLA
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(baos);
			oos.writeObject(resourceDescrip);
			oos.close();
			request.addProperty("arg1", Base64.encode(baos.toByteArray()));
			
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.setOutputSoapObject(request);
			HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
			
			androidHttpTransport.call(SOAP_ACTION, envelope);
			SoapPrimitive  resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();
			id = resultsRequestSOAP.toString();
		} catch (Exception e) {
			Logger.logError(MovirdroidWSInterface.class.getSimpleName(), "Error al agregar índice", e);
		}
		return id;
	}
	
	public String updateIndex(ResourceDescriptionWS resourceDescrip) {
		PeerWS peerWS = this.peerClient.getWSObject();
		SoapObject request = new SoapObject(NAMESPACE, "updateIndex");
		String id = null;
		try {
			PropertyInfo propInfo = new PropertyInfo();
			propInfo.setName("arg0");
			propInfo.setValue(peerWS);
			propInfo.setType(peerWS.getClass());
			request.addProperty(propInfo);
			//SERILIZAR LA DESCRIPCION DEL RECURSO Y MANDARLA
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(baos);
			oos.writeObject(resourceDescrip);
			oos.close();
			request.addProperty("arg1", Base64.encode(baos.toByteArray()));
			
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.setOutputSoapObject(request);
			HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
			
			androidHttpTransport.call(SOAP_ACTION, envelope);
			SoapPrimitive  resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();
			id = resultsRequestSOAP.toString();
		} catch (Exception e) {
			Logger.logError(MovirdroidWSInterface.class.getSimpleName(), "Error al actualizando índice", e);
		}
		return id;
	}
	
	


}
